package com.goldgov.distancelearning.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.authorityInfo.service.AuthorityInfoInit;
import com.goldgov.distancelearning.service.Distancelearning;
import com.goldgov.distancelearning.service.DistancelearningBean;
import com.goldgov.distancelearning.service.DistancelearningCountBean;
import com.goldgov.distancelearning.service.DistancelearningQuery;
import com.goldgov.distancelearning.service.DistancelearningService;
import com.goldgov.distancelearning.service.DistancelearningUser;
import com.goldgov.distancelearning.service.DistancelearningUserQuery;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.securityworkbench.attachment.AttachementBean;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.PropertyUtil;
import com.goldgov.utils.UrlUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

/** 
 * @ClassName: DistancelearningController 
 * @Description: TODO
 */
@RestController
@RequestMapping("/workbench/distancelearning")
@Api("远程教育服务接口")
public class DistancelearningController {
	
	@Autowired
	private DistancelearningService distancelearningService;
	
	@Autowired
	private RemoteCallService remoteCallService;
	
	/**
	 * 查询远程教育
	 * @date 2018年6月22日 下午4:33:00 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/listGetDisByAdmin")
	@ApiOperation(value = "远程教育记录", notes ="查询同级或同级以下记录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
		 @ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
		 @ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
		 @ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
		 @ApiImplicitParam(name = "searchDName", value = "会议名称", paramType = "query"),
		 @ApiImplicitParam(name = "searchParentId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchDisStatus", value = "会议状态", paramType = "query"),
		 @ApiImplicitParam(name = "searchOrganizationId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchIsInclude", value = "是否包含下级单位", paramType = "query") })
	public JsonQueryObject<Distancelearning> getDistancelearningByAdminList(@ApiIgnore DistancelearningQuery query,HttpServletRequest request,Model model){
		//是否包含下级单位
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
//		if (query.getSearchIsInclude() != null && !"".equals(query.getSearchIsInclude())) {
//			if ("1".equals(query.getSearchIsInclude())) {
//				query.setSearchScopeCode(u);
//			}
//		}
		if (query.getSearchOrganizationId() == null || "".equals(query.getSearchOrganizationId())) {
			query.setSearchScopeCode(u);
		}
		List<Distancelearning> list = distancelearningService.getDistancelearningByAdminList(query);
		if(null!=list && list.size()>0) {
			for(Distancelearning d:list) {
				Map params=new HashMap();
				params.put("groupId", d.getDistancelearningID());
				String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
				JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
				JSONArray jsonList=json.getJSONArray("resultList");
				List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
				for(AttachementBean att:ab) {
					att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
					if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
						att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
					}else {
						att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
					}
				}
				d.setFileList(ab);
			}
		}
		
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	/**
	 * 查询远程教育直播列表
	 * @date 2018年6月22日 下午4:33:00 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/listGetDisLiveByAdmin")
	@ApiOperation(value = "远程教育直播列表", notes ="查询同级或同级以下直播列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
		@ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
		@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
		@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
		@ApiImplicitParam(name = "searchDName", value = "会议名称", paramType = "query"),
		@ApiImplicitParam(name = "searchParentId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchChilderOrg", value = "是否包含子部门", paramType = "query"),
		@ApiImplicitParam(name = "searchOrganizationId", value = "管理范围", paramType = "query"),
		@ApiImplicitParam(name = "searchIsInclude", value = "是否包含下级单位", paramType = "query") })
	public JsonQueryObject<Distancelearning> listGetDisLiveByAdmin(@ApiIgnore DistancelearningQuery query,HttpServletRequest request,Model model){
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
		//是否包含下级单位
//		if (query.getSearchIsInclude() != null && !"".equals(query.getSearchIsInclude())) {
//			if ("1".equals(query.getSearchIsInclude())) {
//				String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
//				query.setSearchScopeCode(u);
//			}
//		}
		if (query.getSearchOrganizationId() == null || "".equals(query.getSearchOrganizationId())) {
			query.setSearchScopeCode(u);
		}
		List<Distancelearning> list = distancelearningService.getDisLiveByAdminList(query);
		
		if(null!=list && list.size()>0) {
			for(Distancelearning d:list) {
				Map params=new HashMap();
				params.put("groupId", d.getDistancelearningID());
				String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
				JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
				JSONArray jsonList=json.getJSONArray("resultList");
				List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
				for(AttachementBean att:ab) {
					att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
					if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
						att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
					}else {
						att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
					}
				}
				d.setFileList(ab);
			}
		}
		
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	
	/**
	 * 根据多个会议id查询会议详情
	 * @date 2018年7月5日 下午2:45:33 
	 * @author hanxiangyu
	 * @param ids
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/listGetDisListByIds")
	@ApiOperation(value = "远程教育记录", notes ="查询同级或同级以下记录")
	public JsonSuccessObject<List<Distancelearning>> getDisListByIds(@ApiParam(value = "distancelearningIDs", required = true) @RequestParam("ids") String[] ids,HttpServletRequest request,Model model){
		List<Distancelearning> listByIds = distancelearningService.getDisListByIds(ids);
		if (listByIds.isEmpty()) {
			model.addAttribute("msg", "记录为空!");
		}else {
			model.addAttribute("disList", listByIds);
			model.addAttribute("msg", "成功");
		}
		JsonSuccessObject<List<Distancelearning>> returnResult = new JsonSuccessObject<List<Distancelearning>>(listByIds);
		return returnResult;
	}

	
	
	/**
	 * 查询远程教育录播记录
	 * @date 2018年6月22日 下午4:33:00 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getLBListByAdmin")
	@ApiOperation(value = "远程教育录播记录", notes ="查询同级或同级以下记录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
		 @ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
		 @ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
		 @ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
		 @ApiImplicitParam(name = "searchDName", value = "会议名称", paramType = "query"),
		 @ApiImplicitParam(name = "searchChilderOrg", value = "是否包含子部门", paramType = "query"),
		 @ApiImplicitParam(name = "searchOrganizationId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchParentId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchIsInclude", value = "是否包含下级单位", paramType = "query") })
	public JsonQueryObject<Distancelearning> getLBListByAdmin(@ApiIgnore DistancelearningQuery query,HttpServletRequest request,Model model){
		//是否包含下级单位
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
//		if (query.getSearchIsInclude() != null && !"".equals(query.getSearchIsInclude())) {
//			if ("1".equals(query.getSearchIsInclude())) {
//				query.setSearchScopeCode(u);
//			}
//		}
		if (query.getSearchOrganizationId() == null || "".equals(query.getSearchOrganizationId())) {
			query.setSearchScopeCode(u);
		}
		List<Distancelearning> list = distancelearningService.getLBListByAdmin(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	
	/**
	 * 查询远程教育
	 * @date 2018年6月22日 下午4:33:00 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping
	@ApiOperation(value = "远程教育记录", notes ="查询本人创建及参加的记录")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchBeginDate", value = "开始时间", paramType = "query"),
		 @ApiImplicitParam(name = "searchEndDate", value = "结束", paramType = "query"),
		 @ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
		 @ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query")})
	public JsonQueryObject<Distancelearning> getDistancelearningList(@ApiIgnore DistancelearningQuery query,HttpServletRequest request,Model model){
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
		LoginAuthUser user=LoginAuthUser.getUser(request);
		query.setSearchUserID(user.getEntityID());//发布人id
//		String u = LoginAuthUser.getPortalUserScope(request); //前台获取code
		query.setSearchScopeCode(u);
		List<Distancelearning> list = distancelearningService.getDistancelearningList(query);
		query.setResultList(list);
		return new JsonQueryObject<>(query);
	}
	
	/**
	 * 获取已参加人员列表
	 * @date 2018年6月22日 下午4:33:10 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@GetMapping("/listGetJoinUser")
	@ApiOperation(value = "获取已参加会议出席人列表", notes ="出席人列表查询")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchUserName", value = "用户姓名", paramType = "query"),
		@ApiImplicitParam(name = "searchDistancelearningID", value = "记录id", paramType = "query")})
	public JsonQueryObject<DistancelearningUser> getConferenceList(@ApiIgnore DistancelearningUserQuery query,HttpServletRequest request,Model model){
		List<DistancelearningUser> userList = distancelearningService.getDistancelearningUserList(query);
		query.setResultList(userList);
		return new JsonQueryObject<>(query);
	}
	

	
	/**
	 * 获取会议详情
	 * @date 2018年6月22日 下午4:33:48 
	 * @author hanxiangyu
	 * @param obj
	 * @param request
	 * @return
	 */
	@GetMapping("/getDistanceByID")
	@ApiOperation(value = "获取远程教育会议详情", notes ="获取远程教育会议详情")
	public JsonSuccessObject<Distancelearning> GetDistanceByID(Distancelearning obj,HttpServletRequest request){
		Distancelearning distaance = distancelearningService.getDistaanceByID(obj);
		
		List<DistancelearningUser> headList = distancelearningService.getHeadList(obj.getDistancelearningID());
		if (!headList.isEmpty()) {
			distaance.setHeadList(headList);
		}
		List<DistancelearningUser> leaveList = distancelearningService.getLeaveList(obj.getDistancelearningID());
		if (!leaveList.isEmpty()) {
			distaance.setLeaveList(leaveList);
		}
		List<DistancelearningUser> singList = distancelearningService.getSingList(obj.getDistancelearningID());
		if (!singList.isEmpty()) {
			distaance.setSingList(singList);
		}
		List<DistancelearningUser> defaultList = distancelearningService.getDefaultList(obj.getDistancelearningID());
		if (!defaultList.isEmpty()) {
			distaance.setDefaultList(defaultList);
		}
		List<String> courseIDs = distancelearningService.getAllCourseIds(obj.getDistancelearningID());
		if (!courseIDs.isEmpty()) {
			distaance.setCourseCount(courseIDs.size());
		}
		
		JsonSuccessObject<Distancelearning> returnResult = new JsonSuccessObject<Distancelearning>(distaance);
		return returnResult;
	}
	
//	@RequestMapping("/getLiveId")
//	@ApiOperation(value = "测试直播间id生成规则", notes ="测试直播间id生成规则")
//	public JsonSuccessObject<Integer> getliveId(HttpServletRequest request,Model model){
//		Integer liveId = distancelearningService.getLiveId();
//		JsonSuccessObject<Integer> returnResult = new JsonSuccessObject<Integer>(liveId);
//		return returnResult;
//	}
	
	/**
	 * 查询远程教育录播记录
	 * @date 2018年6月22日 下午4:33:00 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getRandomDis")
	@ApiOperation(value = "远程教育随机记录", notes ="查询同级或同级以下记录")
	public JsonSuccessObject<List<Distancelearning>> getRandomDis(DistancelearningBean disBean,HttpServletRequest request,Model model){
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
		if (disBean.getSearchCount() != null) {
			disBean.setPageSize(disBean.getSearchCount().intValue());
		}
		if (disBean.getSearchOrganizationId() == null || "".equals(disBean.getSearchOrganizationId())) {
			disBean.setSearchScopeCode(u);
		}
		Random random = new Random();
		int countDis = distancelearningService.getCountRandomDis(disBean);
		List<Distancelearning> list = new ArrayList<>();
		if (countDis > 0) {
			if (countDis > disBean.getPageSize()) {
			    int s = random.nextInt(countDis - disBean.getPageSize());
			    disBean.setIndex(s);
			}else {
				disBean.setIndex(0);
			}
		}else {
			disBean.setIndex(0);
		}
		list = distancelearningService.getRandomDis(disBean);
		JsonSuccessObject<List<Distancelearning>> returnResult = new JsonSuccessObject<List<Distancelearning>>(list);
		return returnResult;
	}
	
	/**
	 * 查询远程教育录播记录
	 * @date 2018年6月22日 下午4:33:00 
	 * @author hanxiangyu
	 * @param query
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("/getLBRandomDis")
	@ApiOperation(value = "远程教育随机记录", notes ="查询同级或同级以下记录")
	public JsonSuccessObject<List<Distancelearning>> getLBRandomDis(DistancelearningBean disBean,HttpServletRequest request,Model model){
		String u=LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request);//后台获取code
		if (disBean.getSearchCount() != null) {
			disBean.setPageSize(disBean.getSearchCount().intValue());
		}
		if (disBean.getSearchOrganizationId() == null || "".equals(disBean.getSearchOrganizationId())) {
			disBean.setSearchScopeCode(u);
		}
		Random random = new Random();
		int countDis = distancelearningService.getLBCountRandomDis(disBean);
		List<Distancelearning> list = new ArrayList<>();
		if (countDis > 0) {
			if (countDis > disBean.getPageSize()) {
			    int s = random.nextInt(countDis - disBean.getPageSize());
			    disBean.setIndex(s);
			}else {
				disBean.setIndex(0);
			}
		}else {
			disBean.setIndex(0);
		}
		list = distancelearningService.getLBRandomDis(disBean);
		JsonSuccessObject<List<Distancelearning>> returnResult = new JsonSuccessObject<List<Distancelearning>>(list);
		return returnResult;
	}
	
	/**
	 * 统计远程教育会议次数及时长
	 * @date 2018年8月21日10:28:53
	 * @author lsg
	 */
	@GetMapping("/countTimesAndLength")
	@ApiOperation(value = "统计远程教育会议次数及时长", notes ="统计远程教育会议次数及时长")
	@ApiImplicitParams({@ApiImplicitParam(name = "searchOrganizationId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
		 @ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
		 @ApiImplicitParam(name = "searchMonth", value = "月份", paramType = "query")})
	public JsonSuccessObject<List<DistancelearningCountBean>> countTimesAndLength(@ApiIgnore DistancelearningQuery query,HttpServletRequest request){
		List<DistancelearningCountBean> list = distancelearningService.countTimesAndLength(query);
		for(DistancelearningCountBean bean : list) {
			bean.setAverageCount(bean.getTotalCount()/bean.getOrgNum());
			if(bean.getTotalLength() == null) {
				bean.setTotalLength(0d);
			}
		}
		JsonSuccessObject<List<DistancelearningCountBean>> returnResult = new JsonSuccessObject<List<DistancelearningCountBean>>(list);
		return returnResult;
	}
	
	/**
	 * 按时间统计远程教育会议次数
	 * @date 2018年8月24日17:26:46
	 * @author lsg
	 */
	@GetMapping("/countTimesByTime")
	@ApiOperation(value = "按时间统计远程教育会议次数", notes ="按时间统计远程教育会议次数")
	@ApiImplicitParams({@ApiImplicitParam(name = "searchOrganizationId", value = "管理范围", paramType = "query"),
		 @ApiImplicitParam(name = "searchTimeType", value = "搜索类型，1：年；2：季度；3：月份", paramType = "query")})
	public JsonSuccessObject<List<DistancelearningCountBean>> countTimesByTime(@ApiIgnore DistancelearningQuery query,HttpServletRequest request){
		List<DistancelearningCountBean> list = distancelearningService.countTimesByTime(query);
		int orgNum = distancelearningService.countOrgNumByOrgId(query.getSearchOrganizationId());
		for(DistancelearningCountBean bean : list) {
			bean.setAverageCount(bean.getTotalCount()/orgNum);
			if(bean.getTotalLength() == null) {
				bean.setTotalLength(0d);
			}
		}
		JsonSuccessObject<List<DistancelearningCountBean>> returnResult = new JsonSuccessObject<List<DistancelearningCountBean>>(list);
		return returnResult;
	}
	
	/**
	 * 查询机构下远程教育列表
	 * @date 2018年8月21日10:28:53
	 * @author lsg
	 */
	@GetMapping("/findDistancelearningListByOrgId")
	@ApiOperation(value = "查询机构下远程教育列表", notes ="查询机构下远程教育列表")
	@ApiImplicitParams({@ApiImplicitParam(name = "searchOrganizationId", value = "管理范围", paramType = "query"),
		@ApiImplicitParam(name = "searchYear", value = "年份", paramType = "query"),
		@ApiImplicitParam(name = "searchQuqrter", value = "季度", paramType = "query"),
		@ApiImplicitParam(name = "searchMonth", value = "月份", paramType = "query"),
		@ApiImplicitParam(name = "currentPage", value = "当前页", paramType = "query"),
		@ApiImplicitParam(name = "pageSize", value = "每页条数", paramType = "query")})
	public JsonSuccessObject<DistancelearningQuery> findDistancelearningListByOrgId(@ApiIgnore DistancelearningQuery query,HttpServletRequest request){
		List<Distancelearning> list = distancelearningService.findDistancelearningListByOrgId(query);
		query.setResultList(list);
		JsonSuccessObject<DistancelearningQuery> returnResult = new JsonSuccessObject<DistancelearningQuery>(query);
		return returnResult;
	}
	
}
